# coding: utf-8
import cv2
import numpy as np
import matplotlib.pyplot as plt
from os import path



def bmp2c(file_name):
        #设置颜色深度为 4bpp
        k = 4
        string_start = ("#include \"lvgl.h\"     \n\
                                                \n\
#ifndef LV_ATTRIBUTE_MEM_ALIGN          \n\
#define LV_ATTRIBUTE_MEM_ALIGN          \n\
#endif                                  \n\
                                        \n\
#ifndef LV_ATTRIBUTE_IMG_ICON           \n\
#define LV_ATTRIBUTE_IMG_ICON           \n\
#endif                                  \n\
                                        \n\
                                        \n\
const LV_ATTRIBUTE_MEM_ALIGN LV_ATTRIBUTE_IMG_ICON uint8_t ")

        array_path = file_name.split(".")
        array_path = ".".join(array_path[:len(array_path)-1])
        array_name = file_name.split("/")[-1]
        array_name = array_name.split('.')[0]
        #创建数组文件并打开
        file = open(array_path+".c", "w+")
        file.write(string_start + array_name+"_map" + "[] = {\n")
        #读取原始图像
        img = cv2.imread(file_name, cv2.IMREAD_UNCHANGED)
        cv2.imshow("img", img)
        height = img.shape[0]
        width = img.shape[1]


        #图像二维像素转换为一维
        data = img.reshape((-1,3))
        data = np.float32(data)



        #定义中心 (type,max_iter,epsilon)
        criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)

        #设置标签
        flags = cv2.KMEANS_RANDOM_CENTERS

        #K-Means聚类 聚集成4类
        compactness, labels, centers = cv2.kmeans(data, 2**k, None, criteria, 10, flags)
        #图像转换回uint8二维类型
        centers = np.uint8(centers)

        #填写索引信息
        for i in range(2**k):
                array = centers[i]
                file.write("\t0x" + '{:0>2x}'.format(array[0]) + ', ' + "0x" + '{:0>2x}'.format(array[1]) + ', ' + "0x" + '{:0>2x}'.format(array[2]) + ', ' + "0x" + '{:0>2x}'.format(0xff) + ', ' + "\t\t/*Color of index " + str(i) + "*/\n")

        file.write("\n\n\t")
        bit_cnt = 8 / k

        for y in range(height):
                bit_val = 0
                for x in range(width):
                        temp = labels[x + y * width][0]
                        if (x + 1) % bit_cnt == 0:
                                bit_val |= temp
                                file.write(" 0x" + '{:0>2x}'.format(bit_val) + ',')
                                bit_val = 0
                        elif (x + 1) % bit_cnt == 1:
                                bit_val |= temp << (8-k)
                                if x == width-1:
                                        file.write(" 0x" + '{:0>2x}'.format(bit_val) + ',')
                file.write("\n\t")


                

        # for i in range(len(labels)):
        #         bit_val |= labels[i][0]
        #         if (0 == ((i + 1) % bit_cnt) and 0 != i) or k == 8:
        #                 file.write(" 0x" + '{:0>2x}'.format(bit_val) + ',')
        #                 bit_val = 0
        #                 if (i + 1) % width == 0 and i != 0:
        #                         file.write("\n\t")
        #         else:
        #                 bit_val <<=  k

                                
        file.write('\n};\n\n'+"lv_img_dsc_t " + array_name+" = {\n")
        file.write("\t.header.always_zero = 0,\n")
        file.write("\t.header.w = "+str(width)+",\n")
        file.write("\t.header.h = "+str(height)+",\n")
        file.write("\t.data_size ="+str(int(height*((width+1)>>2)/bit_cnt)+4*2**k)+",\n")
        file.write("\t.header.cf = "+"LV_IMG_CF_INDEXED_"+str(k)+"BIT"+",\n")
        file.write("\t.data = "+array_name+"_map"+",\n};")

        file.close()


